package com.edu.bean;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MyIOC2 {

    //需要一条属性来存多个 不确定类型的对象
    Map<String,Object> map = new HashMap();
    private String filePath;//配置文件路径
    private Document document;//解析后的文档

    public MyIOC2(String path){
        this.filePath = path;
        init();
    }

    //解析 xml格式的配置文件
    public void init()  {
        InputStream inputStream = MyIOC2.class.getClassLoader().getResourceAsStream(filePath);
        SAXReader reader = new SAXReader();//用于读xml格式的文件
        try {
            document = reader.read(inputStream);
            Element root = document.getRootElement();//获取跟节点//beans
            List<Element> elements = root.elements();//获取根节点里所有的子节点bean
            for (Element element : elements) {  //遍历 根节点的子节点 遍历各个bean
                if("bean".equals(element.getName())) {
                    Node id = element.attribute("id");
                    Node clazz = element.attribute("class");
                    if(id != null && clazz != null){
                        String idName = id.getStringValue();
                        String clazzName = clazz.getStringValue();
                        putObject(idName,clazzName);
                        //判断 当前对象 有没有一些属性
                        List<Element> properties = element.elements();
                        for (Element property : properties) {
                            System.out.println(property);
                            Node pro = property.attribute("name");
                            Node value = property.attribute("value");
                            String proName = pro.getStringValue();
                            String valueString = value.getStringValue();
                            System.out.println(proName+":"+valueString);
                        }
                    }
                }
            }
        } catch (DocumentException e) {
            System.out.println("读取配置文件异常");
            e.printStackTrace();
        }

    }

    public void putObject(String id,String className){
        try {
            Class<?> aClass = Class.forName(className);
            map.put(id,aClass.newInstance());
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }

    @Override
    public String toString() {
        return "MyIOC2{" +
                "map=" + map +
                '}';
    }
}
